﻿using Oplug.EntityFramework;
using Oplug.EntityFramework.RossLive;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Oplug.Services
{
    public class UserService : IDisposable
    {
        public OplugLiveDbContext dbContext;
        public IRepository<RossUsers, int> repository;
        public IRepository<Departments, int> department;
        public UserService(string nameOrConnectionString)
        {
            dbContext = new OplugLiveDbContext(nameOrConnectionString);
            repository = new Repository<RossUsers, int>(dbContext);
            department = new Repository<Departments, int>(dbContext);
        }
        public List<RossUsers> GetSelfAndChildUsers(string UserId)
        {
            List<RossUsers> lists = new List<RossUsers>();
            var user = repository.GetAllList(o => o.UserID == UserId).FirstOrDefault();
            if (user != null)
            {
                var LeaderDepts = department.GetAllList(o => o.Leader == user.UserID || o.Leader == user.UserName);
                var firstDept = LeaderDepts.Where(o => o.Depth == 1).ToList();
                if (firstDept.Count > 0)
                {
                    foreach (var item in firstDept)
                    {
                        var users = repository.GetAllList(o => o.DepartCode == item.DepartCode);
                        lists=  lists.Union(users).ToList();
                    }
                }
                else
                {
                    var twoDept = LeaderDepts.Where(o => o.Depth == 2).ToList();
                    if (twoDept.Count > 0)
                    {
                        foreach (var item in twoDept)
                        {
                            var users = repository.GetAllList(o => o.ClassCode == item.DepartCode);
                            lists = lists.Union(users).ToList();
                        }
                    }
                    else
                    {
                        var thdDept = LeaderDepts.Where(o => o.Depth == 3).ToList();
                        foreach (var item in thdDept)
                        {
                            var users = repository.GetAllList(o => o.GroupCode == item.DepartCode);
                            lists = lists.Union(users).ToList();
                        }
                    }
                }
            }
            lists = lists.Distinct().ToList();
            return lists;
        }

        public void GetSelfAndChildDepartment(int ParentId, List<Departments> result)
        {
            var root = department.Get(ParentId);
            result.Add(root);
            var items = department.GetAllList(o => o.ParentId == ParentId);
            foreach(var item in items)
            {
                GetSelfAndChildDepartment(item.ID, result);
            }
        }
        public void Dispose()
        {
            dbContext.Dispose();
        }
    }
}
